package com.bx.implatform.service;

import com.bx.imcommon.contant.IMConstant;
import com.bx.imcommon.contant.IMRedisKey;
import com.bx.imcommon.model.User;
import com.ruoyi.common.core.domain.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class TokenService {
    // 令牌秘钥
    @Value("${jwt.accessToken.secret:abcdefghijklmnopqrstuvwxyz}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${jwt.accessToken.expireIn:1800}")
    private int expireTime;
    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    public static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Resource
    private RedisCache redisCache;

    @Resource
    private RedisConnectionFactory factory;

    private RedisTemplate<String, String> rt = null;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(IMConstant.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                log.info("原始key：" + userKey);
                fetchRedisTemplate();
                ValueOperations<String, String> ops = rt.opsForValue();
                String str = ops.get(userKey);
                log.info("原始数据：" + str);
                String nickName = fuckJsonString(str, "nickName");
                String userName = fuckJsonString(str, "userName");
                Long userId = fuckJsonLong(str, "userId");
                Integer terminal = fuckJsonInteger(str, "terminal");


                User user = new User();
                user.setUserName(userName);
                user.setNickName(nickName);
                user.setId(Long.valueOf(userId));

                LoginUser loginUser = new LoginUser();
                loginUser.setUser(user);
                loginUser.setUserId(userId);
                loginUser.setTerminal(terminal);
                return loginUser;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    private Integer fuckJsonInteger(String str, String key) {
        int index = str.indexOf(key);
        index = str.indexOf(":", index);
        char c = str.charAt(index);
        while (c < '0' || c > '9') {
            c = str.charAt(++index);
        }
        Integer ans = 0;
        while (c >= '0' && c <= '9') {
            ans = ans * 10 + (c - '0');
            c = str.charAt(++index);
        }
        return ans;
    }

    private Long fuckJsonLong(String str, String key) {
        int index = str.indexOf(key);
        index = str.indexOf(":", index);
        char c = str.charAt(index);
        while (c < '0' || c > '9') {
            c = str.charAt(++index);
        }
        Long ans = 0L;
        while (c >= '0' && c <= '9') {
            ans = ans * 10 + (c - '0');
            c = str.charAt(++index);
        }
        return ans;
    }

    private String fuckJsonString(String str, String key) {
        int index = str.indexOf(key);
        index = str.indexOf(":", index);
        int left = str.indexOf("\"", index);
        int right = str.indexOf("\"", left + 1);
        if (left == -1 || right == -1) {
            return "";
        }
        return str.substring(left + 1, right).trim();
    }

    private void fetchRedisTemplate() {
        if (rt == null) {
            rt = new RedisTemplate<>();
            rt.setConnectionFactory(factory);
            rt.setKeySerializer(new StringRedisSerializer());
            rt.setHashKeySerializer(new StringRedisSerializer());
            rt.setValueSerializer(new StringRedisSerializer());
            rt.setHashValueSerializer(new StringRedisSerializer());
            rt.afterPropertiesSet();
        }
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (Objects.nonNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    private String getTokenKey(String uuid) {
        return IMRedisKey.LOGIN_TOKEN_KEY + uuid;
    }

    public int getExpireTime() {
        return expireTime;
    }
}
